<template>
  <view class="sign-wrapper">
    <canvas
      id="firstCanvas"
      class="firstCanvas"
      canvas-id="firstCanvas"
      disable-scroll="true"
      @touchmove="move"
      @touchstart="start($event)"
      @touchend="end"
      @touchcancel="cancel"
      @longtap="tap"
      @error="error"
    />
    <view class="sign-btn-wrapper">
      <button class="sign-btn reset" @tap="clearClick">重写</button>
      <button class="sign-btn done" @tap="overSign">确认</button>
    </view>
  </view>
</template>
<script>
export default {
  data() {
    return {
      signImage: "",
      id: '',
      isEnd: false, // 是否签名
      touches: [],
      canvasw: 0,
      canvash: 0,
      content: null
    };
  },
  created() {},
  methods: {
    overSign() {
      if (this.isEnd) {
        uni.canvasToTempFilePath({
          canvasId: "firstCanvas",
          success: (res) => {
            // 打印图片路径
            // 设置图片
            this.signImage = res.tempFilePath
            let image = null
            // #ifdef H5
            image = document.getElementById('firstCanvas').toDataURL('image/png')
            uni.setStorageSync('sign', image)
            uni.navigateBack()
            // #endif
            // #ifdef MP-WEIXIN
            wx.getFileSystemManager().readFile({
              filePath: this.signImage,
              encoding: "base64",
              success: (res) => {
                // 返回base64编码结果，但是图片的话没有data:image/png
                image = `data:image/png;base64,${res.data}`
                uni.setStorageSync('sign', image)
                uni.navigateTo({
                  // url: `/contract/sign?id=${this.id}`
                  url: `/contract/sign_new?id=${this.id}`
                })
              },
              fail: (err) => {
                uni.showToast({
                  title: err.message,
                  icon: "none",
                  duration: 2000
                })
              }
            })
            // #endif
          },
          fail: function(err){
            uni.showToast({
              title: err.message,
              icon: "none",
              duration: 2000
            })
          }
        });
      } else {
        uni.showToast({
          title: "请先完成签名",
          icon: "none",
          duration: 2000,
          mask: true
        })
      }
    },
    // 画布的触摸移动开始手势响应
    start(event) {
      // 获取触摸开始的 x,y
      const point = {
        x: event.changedTouches[0].x,
        y: event.changedTouches[0].y
      }
      const tempTouches = JSON.parse(JSON.stringify(this.touches))
      tempTouches.push(point)
      this.touches = tempTouches
    },
    // 画布的触摸移动手势响应
    move(e) {
      const point = {
        x: e.touches[0].x,
        y: e.touches[0].y
      }
      const tempTouches = JSON.parse(JSON.stringify(this.touches))
      tempTouches.push(point)
      this.touches = tempTouches
      if (this.touches.length >= 2) {
        this.draw()
      }
    },
    // 画布的触摸移动结束手势响应
    end(e) {
      // 设置为已经签名
      this.isEnd = true;
      // 清空轨迹数组
      this.touches = []
    },
    // 画布的触摸取消响应
    cancel(e) {
      // console.log("触摸取消" + e);
      this.isEnd = true;
      this.touches = []
    },
    // 画布的长按手势响应
    tap(e) {
      // console.log("长按手势" + e);
    },
    error(e) {
      // console.log("画布触摸错误" + e);
      this.isEnd = true;
      this.touches = []
    },
    // 绘制
    draw() {
      const point1 = this.touches[0];
      const point2 = this.touches[1];
      const tempTouches = JSON.parse(JSON.stringify(this.touches))
      tempTouches.shift()
      this.touches = tempTouches
      this.content.moveTo(point1.x, point1.y)
      this.content.lineTo(point2.x, point2.y)
      this.content.stroke()
      this.content.draw(true)
    },
    // 清除操作
    clearClick() {
      // 设置为未签名
      this.isEnd = false;
      // 清除画布
      this.content.clearRect(0, 0, this.canvasw + this.canvash, this.canvasw + this.canvash);
      this.content.draw(true);
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.id) {
      this.id = options.id
    } else {
      this.id = uni.getStorageSync('contractIdP')
    }
    // if (uni.getStorageSync("signFrom")) {
    //   uni.removeStorageSync('signFrom');
    // } 
    // uni.hideLoading();
    // 获取设备信息
    const res = uni.getSystemInfoSync();
    this.canvasw = res.windowWidth
    this.canvash = res.windowHeight
    // 获得Canvas的上下文
    this.content = uni.createCanvasContext("firstCanvas");
    // 设置线的颜色
    this.content.setStrokeStyle("#000");
    // 设置线的宽度
    this.content.setLineWidth(5);
    // 设置线两端端点样式更加圆润
    this.content.setLineCap("round");
    // 设置两条线连接处更加圆润
    this.content.setLineJoin("round");
  }
};
</script>
